<template>
    <div class="editPermission">
        <el-dialog :visible.sync="centerDialogVisible" :close-on-click-modal="clickModalHide" :before-close="closeDialog" 
        		width="60%" :title="type=='add'?'添加角色':'修改角色'"
        >
            <el-form :model="editData" size="mini" status-icon :rules="rules" ref="editData" label-width="100px" class="demo-ruleForm">
                <el-form-item label="角色名称：" prop="roleName">
                    <el-input v-model="editData.roleName" style="width: 72%;"></el-input>
                </el-form-item>
                <el-form-item label="角色类型：" prop="roleType">
                    <el-radio v-model="editData.roleType" label="1">超级管理员</el-radio>
                    <el-radio v-model="editData.roleType" label="0">普通角色</el-radio>
                </el-form-item>
                <el-form-item label="角色权限：" prop="rolePermission" v-show="editData.roleType == 0">
                    <div class="scroll-p-div">
                        <el-tree ref="pTree" default-expand-all :data="permissionList" show-checkbox node-key="id" :props="defaultProps"></el-tree>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm('editData')">提交</el-button>
                    <el-button @click="resetForm('editData')">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>
<script>
    export default {
        name: "editPermission",
        props: ["dataDetail", "type"],
        data() {
            var notEmpty = (rule, value, callback) => {
                if(!value) {
                    return callback(new Error("不能为空"));
                } else {
                    callback();
                }
            };
            return {
                defaultProps: {
                    children: "children",
                    label: "moduleName"
                },
                centerDialogVisible: false,
                clickModalHide: false,
                permissionList: [],
                editData: {
                    id: "",
                    roleType: "1",
                    rolePermission: "",
                    roleName: ""
                },
                rules: {
                    roleName: [{
                        validator: notEmpty,
                        trigger: "blur"
                    }]
                },
                count: 0
            };
        },
        mounted() {
            this.getAllPermission();
        },
        methods: {
            getAllPermission() {
                let self = this;
                self.$http({
                    url: "/autoMonitor/permission/queryAllPermission",
                    method: "post"
                }).then(resp => {
                    if(resp.success) {
                        self.permissionList = resp.result;
                        console.log(self.permissionList)
                    }
                });
            },
            operateLogin() {
                let self = this;
                let permission = self.editData.roleType == 0 ? self.getCheckedNodes() : "";
                self.editData.rolePermission = permission;
                let url = this.type == "add" ? "/autoMonitor/permission/addPermission" : "/autoMonitor/permission/updatePermission";
                if(this.count == 0) {
                    self.$http({
                        url: url,
                        method: "post",
                        data: JSON.stringify(self.editData),
                        dataType: "json",
                        contentType: "application/json"
                    }).then(resp => {
                        self.resetForm("editData");
                        if(resp.success) {
                            self.$eventBus.$emit("updatePermission");
                            self.$notify({
                                title: "提示",
                                message: "操作成功！",
                                type: "success"
                            });
                            return;
                        }
                        self.$notify({
                            title: "提示",
                            message: "操作失败",
                            type: "error"
                        });
                        this.count--;
                    });
                    this.count++;
                }
            },
            //关闭弹窗
            closeDialog() {
                this.$refs["editData"].clearValidate();
                this.centerDialogVisible = false;
            },
            submitForm(formName) {
                let self = this;
                this.$refs[formName].validate(valid => {
                    if(valid) {
                        self.operateLogin();
                    } else {
                        return false;
                    }
                });
            },
            resetForm(formName) {
                this.$refs[formName].clearValidate();
                this.closeDialog();
            },
            getCheckedNodes() {
                let permission = "";
                let checkData = this.$refs.pTree.getCheckedNodes() || [];
                for(let data of checkData) {
                    let _p = data.permission;
                    permission += _p + ",";
                }
                permission = permission ? permission.substring(0, permission.length - 1) : permission;
                return permission;
            },
            setCheckBox() {
                if(this.type == "edit") {
                    let check = [];
                    let permission = this.editData.rolePermission || "";
                    let list = permission.split(",");
                    this.setTreeCheck(this.permissionList, list, check);
                    this.$refs.pTree.setCheckedNodes(check);
                }
            },
            setTreeCheck(permissionList, list, check) {
                if(permissionList && permissionList.length > 0) {
                    for(let _p of permissionList) {
                        let rolePermission = _p.permission;
                        if(list.indexOf(rolePermission) > -1) {
                            check.push(_p);
                        }
                        this.setTreeCheck(_p.children, list, check);
                    }
                }
            },
			      arraySpanMethod({ row, columnIndex }) {
				        if (columnIndex < 2) {
					          if (row.span === 0) {
					            	return [0, 0]
					          } else {
					            	return [row.span, 1]
					          }
				        }
			      },
        },
        watch: {
            dataDetail(val) {
                let self = this;
                this.count = 0;
                this.centerDialogVisible = true;
                for(let key in this.editData) {
                    if(!val.hasOwnProperty(key)) {
                        val[key] = "";
                    }
                }
                this.editData = val;
                self.$nextTick(() => {
                    self.$refs.pTree.setCheckedKeys([]);
                    self.setCheckBox();
                });
            }
        }
    };
</script>
<style scoped>
    .editPermission .el-dialog__body {
        padding: 0px 20px;
    }
    .editPermission .el-form-item {
        margin-bottom: 12px;
    }
    .editPermission .el-input--mini .el-input__inner {
        height: 26px;
    }
    .editPermission .el-radio {
        margin-right: 5px;
    }
    .scroll-p-div {
        height: 240px;
        overflow-x: hidden;
        overflow-y: auto;
    }
</style>